package com.gzgy.ustore.api.service.impl;

import com.gzgy.ustore.api.common.exception.BaseAPIException;
import com.gzgy.ustore.api.common.util.Constant;
import com.gzgy.ustore.api.common.util.DateUtil;
import com.gzgy.ustore.api.common.util.PushUtil;
import com.gzgy.ustore.api.dao.PushLogDao;
import com.gzgy.ustore.api.service.PushService;
import com.ustore.model.PushLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PushServiceImpl implements PushService {

    @Autowired
    private PushLogDao pushLogDao;

    @Override
    public String pushMessage(String title, String message) {
        //push 操作
        String result = PushUtil.pushAllAndroid(Constant.accessId, Constant.secretKey, title, message);
        if (result.equals("发送信息成功")) {
            //add push log
            PushLog pushLog = new PushLog();
            pushLog.setPushDevice("");
            pushLog.setPushMessage(message);
            pushLog.setPushTitle(title);
            pushLog.setCreatedBy("admin");
            pushLog.setCreatedTime(DateUtil.getCurrentDate());
            pushLog.setPushType(0);
            pushLogDao.add(pushLog);
        } else {
            throw new BaseAPIException("信息发送失败");
        }
        return result;
    }

    @Override
    public String pushMessage(String title, String message, String deviceToken) {
        //push 操作
        String result = PushUtil.pushTokenAndroid(Constant.accessId, Constant.secretKey, title, message, deviceToken);
        if (result.equals("发送信息成功")) {
            //add push log
            PushLog pushLog = new PushLog();
            pushLog.setPushDevice(deviceToken);
            pushLog.setPushMessage(message);
            pushLog.setPushTitle(title);
            pushLog.setPushType(1);
            pushLog.setCreatedBy("admin");
            pushLog.setCreatedTime(DateUtil.getCurrentDate());
            pushLogDao.add(pushLog);
        } else {
            throw new BaseAPIException("信息发送失败");
        }
        return result;
    }

    @Override
    public Map<String, Object> pushMessageList(int index, int page,Integer type ,String deviceToken) {
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("index",index);
        int count = pushLogDao.pushLogCount(type,deviceToken);
        map.put("count",count);
        List<PushLog> list = new ArrayList<PushLog>();
        if(count >0){
            list = pushLogDao.pushList(type,deviceToken,index,page);
        }
        map.put("pushList",list);
        return map;
    }
}
